<template>
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备编号" prop="code">
                <el-input
                    v-model="queryParams.code"
                    placeholder="请输入设备编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="bizScreenList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="名称" align="center" prop="name"/>
            <el-table-column label="设备编号" align="center" prop="code"/>
            <el-table-column label="产品" align="center" prop="productId"/>
            <el-table-column label="状态" align="center" prop="isOnline">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.isOnline==='1'?'success':'info'">
                        {{ scope.row.isOnline === '1' ? '在线' : '离线' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="sensorShow(scope.row)"
                    >信息点展示
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改屏幕对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="项目" prop="projectId">
                    <el-select v-model="form.projectId"
                               placeholder="请选择项目"
                               filterable
                               clearable
                    >
                        <el-option
                            v-for="item in projectList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="名称" prop="name" >
                    <el-input v-model="form.name" placeholder="请输入名称"/>
                </el-form-item>
                <el-form-item label="设备编号" prop="code">
                    <el-input v-model="form.code" placeholder="请输入设备编号"/>
                </el-form-item>
                <el-form-item label="产品" prop="productId" >
                    <el-select v-model="form.productId"
                               placeholder="选择产品"
                               clearable
                    >
                        <el-option
                            v-for="item in productList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="分组" prop="groupIds" >
                    <el-select v-model="form.groupConfig1.groupIds"
                               placeholder="请选择分组"
                               clearable
                               multiple
                    >
                        <el-option
                            v-for="item in groupList"
                            :key="item.id"
                            :label="item.groupName"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="分组间隔(秒)" prop="interval">
                    <el-input-number v-model="form.groupConfig1.interval" :min="0"></el-input-number>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改控制点分组对话框 -->
        <el-dialog title="屏幕展示信息点" :visible.sync="screenSensorOpen" width="1500px" append-to-body>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        size="mini"
                        @click="addSensor"
                    >添加信息点
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        size="mini"
                        @click="batchEdit"
                    >批量编辑
                    </el-button>
                </el-col>

            </el-row>
            <el-table :data="screenSensorList">

                <el-table-column label="序号" align="center" width="80">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>

                <el-table-column label="关联信息点" align="center" prop="relationSensor" width="100">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.relationSensor">是</el-checkbox>
                    </template>
                </el-table-column>

                <el-table-column label="网关" align="center" prop="gatewayId" width="300">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.gatewayId"
                                   placeholder="选择网关"
                                   v-if="scope.row.relationSensor"
                                   filterable
                                   clearable
                                   style="width: 250px"
                        >
                            <el-option
                                v-for="item in gatewayList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                @click.native="tableChangeGateway(item.value, scope.$index)"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="信息点" align="center" prop="sensorId" width="150">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.sensorId"
                                   placeholder="选择信息点"
                                   v-if="scope.row.relationSensor"
                                   filterable
                                   clearable
                        >
                            <el-option
                                v-for="item in scope.row.sensorSelect"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="信息点别名" align="center" prop="sensorAlias">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.relationSensor" v-model="scope.row.sensorAlias"
                                  placeholder="请输入信息点别名"
                        ></el-input>
                    </template>
                </el-table-column>

                <el-table-column label="格式" align="center" prop="format">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.format"
                                   placeholder="选择格式"
                                   clearable
                                   v-if="scope.row.relationSensor"
                        >
                            <el-option
                                v-for="item in formatList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="自定义消息" align="center" prop="customMessage">
                    <template slot-scope="scope">
                        <el-input v-if="!scope.row.relationSensor" v-model="scope.row.customMessage"
                                  placeholder="请输入自定义消息"
                        ></el-input>
                    </template>
                </el-table-column>


                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-link style="margin-left: 5px" type="primary" :underline="false"
                                 @click="moveUp(scope.row, scope.$index)"
                        >上移
                        </el-link>
                        <el-link style="margin-left: 10px" type="primary" :underline="false"
                                 @click="moveDown(scope.row, scope.$index)"
                        >下移
                        </el-link>
                        <el-link style="margin-left: 10px" type="primary" :underline="false"
                                 @click="openSensor(scope.row, scope.$index)"
                        >编辑
                        </el-link>
                        <el-link style="margin-left: 10px" type="danger" :underline="false"
                                 @click="deleteSensor(scope.row, scope.$index)"
                        >删除
                        </el-link>
                    </template>
                </el-table-column>

            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitScreenSensor">确 定</el-button>
                <el-button @click="cancelScreenSensor">取 消</el-button>
            </div>
        </el-dialog>


<!--        单个位置编辑-->
        <el-dialog title="编辑" :visible.sync="screenSensorLocationOpen" width="1200px" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-table :data="form.screenSensorLocationList" v-if="form.productId==='C-PM-4G-001'">
                    <el-table-column label="序号" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.orderNum + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="x轴(字节)" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaX"
                                      placeholder="请输入x轴数值"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="y轴(像素)" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaY"
                                      placeholder="请输入Y轴数值"
                            ></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="宽度(字节)" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaWidth"
                                      placeholder="请输入宽度"
                            ></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="高度(像素)" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaHeight"
                                      placeholder="请输入高度"
                            ></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="字体对齐方式" align="center">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.textAlignment"
                                       placeholder="选择字体对齐方式"
                                       clearable
                            >
                                <el-option
                                    v-for="item in textAlignmentList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </template>
                    </el-table-column>

                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFormLocation">确 定</el-button>
            </div>
        </el-dialog>


        <!--        批量编辑-->
        <el-dialog title="批量编辑" :visible.sync="screenSensorLocationBatchOpen" width="1200px" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-button @click="addConfig" v-if="form.productId==='C-PM-4G-001'">添加</el-button>
                <el-table :data="form.config1" v-if="form.productId==='C-PM-4G-001'">
                    <el-table-column label="序号" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.orderNum + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="x轴" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaX"
                                      placeholder="请输入x轴数值"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="y轴" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaY"
                                      placeholder="请输入Y轴数值"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="宽度" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaWidth"
                                      placeholder="请输入宽度"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="高度" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.areaHeight"
                                      placeholder="请输入高度"
                            ></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="字体对齐方式" align="center">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.textAlignment"
                                       placeholder="选择字体对齐方式"
                                       clearable
                            >
                                <el-option
                                    v-for="item in textAlignmentList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </template>
                    </el-table-column>


                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-link style="margin-left: 5px" type="danger" :underline="false"
                                     @click="deleteScreenLocation(scope.row, scope.$index)"
                            >删除
                            </el-link>
                        </template>
                    </el-table-column>

                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listBizScreen,
    getBizScreen,
    delBizScreen,
    addBizScreen,
    updateBizScreen,
    addScreenSensor,
    getScreenSensor
} from '@/api/equipment/bizScreen'
import { listSelectByGatewayId } from '@/api/equipment/sensor'
import { listSelect } from '@/api/equipment/gateway'
import Template from '@/views/system/notify/my/index.vue'
import { mapGetters } from 'vuex'
import { getGroupSelect } from '@/api/equipment/group'

export default {
    name: 'BizScreen',
    components: { Template },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 屏幕表格数据
            bizScreenList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                code: null,
                status: null
            },
            // 表单参数
            form: {
                id: null,
                name: null,
                code: null,
                status: '0',
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                productId: null,
                projectId: this.projectId,
                config1: [],
                groupConfig1:{
                    groupIds:[],
                    interval:null
                }
            },
            // 表单校验
            rules: {
                name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '标识不能为空', trigger: 'blur' }
                ]
            },
            gatewayList: [],
            screenSensorList: [],
            configList: [],
            screenSensorOpen: false,
            screenSensorLocationOpen: false,
            screenSensorLocationBatchOpen: false,
            productList: [
                { label: 'C-PM-4G-001', value: 'C-PM-4G-001' }
            ],
            formatList: [
                { label: '信息点别名: 信息点数值', value: 'alias: value' },
                { label: '信息点数值', value: 'value' },
            ],
            textAlignmentList: [
                { label: '左对齐', value: 0 },
                { label: '右对齐', value: 1 },
                { label: '居中对齐', value: 2 }
            ],
            groupList:[]
        }
    },
    created() {
        this.getList()
        this.getGatewayList()
        this.getGroupList()
    },
    computed:{
        ...mapGetters([
            'projectId',
            'projectList'
        ])
    },
    methods: {
        // 分组
        getGroupList(){
            getGroupSelect().then(res=>{
                this.groupList = res.data
            })
        },
        getList() {
            this.loading = true
            listBizScreen(this.queryParams).then(response => {
                this.bizScreenList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                id: null,
                name: null,
                code: null,
                status: '0',
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                productId: null,
                projectId: this.projectId,
                config1: [],
                groupConfig1:{
                    groupIds:[],
                    interval:null
                }
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加屏幕'
        },

        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getBizScreen(id).then(response => {
                if(response.data.groupConfig1===null){
                    response.data.groupConfig1 = {
                        groupIds:[],
                        interval:null
                    }
                }
                this.form = response.data
                this.open = true
                this.title = '修改屏幕'
                // this.configList = configParse
            })
        },
        batchEdit() {
            getBizScreen(this.form.id).then(response => {
                if(response.data.groupConfig1===null){
                    response.data.groupConfig1 = {
                        groupIds:[],
                        interval:null
                    }
                }
                this.form = response.data
                this.screenSensorLocationBatchOpen = true
                // this.configList = configParse
            })
        },
        sensorShow(row) {
            this.form.id = row.id
            getScreenSensor(row.id).then(response => {
                this.screenSensorList = response.data
                this.screenSensorOpen = true
            })
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateBizScreen(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.screenSensorLocationBatchOpen = false
                            this.getList()
                        })
                    } else {
                        addBizScreen(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        submitFormLocation() {
            this.form.config1.forEach(item => {
                if (item.orderNum === this.form.screenSensorLocationList[0].orderNum) {
                    item.orderNum = this.form.screenSensorLocationList[0].orderNum
                    item.areaX = this.form.screenSensorLocationList[0].areaX
                    item.areaY = this.form.screenSensorLocationList[0].areaY
                    item.areaWidth = this.form.screenSensorLocationList[0].areaWidth
                    item.areaHeight = this.form.screenSensorLocationList[0].areaHeight
                    item.textAlignment = this.form.screenSensorLocationList[0].textAlignment
                }
            })
            if (this.form.screenSensorLocationList[0].orderNum === this.form.config1.length) {
                this.form.config1.push(this.form.screenSensorLocationList[0])
            }
            updateBizScreen(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.screenSensorLocationOpen = false
                this.getList()
            })
        },
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除屏幕编号为"' + ids + '"的数据项？').then(function() {
                return delBizScreen(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('stock/bizScreen/export', {
                ...this.queryParams
            }, `bizScreen_${new Date().getTime()}.xlsx`)
        },
        addSensor() {
            let obj = {
                relationSensor: true,
                screenId: this.form.id,
                gatewayId: null,
                sensorId: null,
                sensorAlias: '',
                customMessage: '',
                sensorSelect: [],
                sensorOrderNumber: this.screenSensorList.length,
                format: null
            }
            this.screenSensorList.push(obj)
        },
        addConfig() {
            let obj = {
                orderNum: this.form.config1.length,
                areaX: null,
                areaY: null,
                areaWidth: null,
                areaHeight: null,
                textAlignment: null
            }
            this.form.config1.push(obj)
        },
        openSensor(row, index) {
            row.sensorOrderNumber = index + 1
            getBizScreen(this.form.id).then(response => {
                if(response.data.groupConfig1===null){
                    response.data.groupConfig1 = {
                        groupIds:[],
                        interval:null
                    }
                }
                this.form = response.data
                for (let item of this.form.config1) {
                    if (item.textAlignment === undefined) {
                        item.textAlignment = null
                    }
                }
                this.form.screenSensorLocationList = []
                if (this.form.config1.length > 0) {
                    this.form.screenSensorLocationList = JSON.parse(JSON.stringify(this.form.config1))
                }
                let newConfig1 = this.form.screenSensorLocationList.filter(item => {
                    return (item.orderNum + 1) === (row.sensorOrderNumber)
                })
                console.log(newConfig1)
                if (newConfig1.length === 0) {
                    let obj = {
                        orderNum: index,
                        areaX: null,
                        areaY: null,
                        areaWidth: null,
                        areaHeight: null,
                        textAlignment: null
                    }
                    newConfig1.push(obj)
                }
                this.form.screenSensorLocationList = JSON.parse(JSON.stringify(newConfig1))
                this.screenSensorLocationOpen = true
                console.log(this.form.screenSensorLocationList)
                // this.configList = configParse
            })
        },
        moveUp(row,index){
            if (index === 0) {
                this.$message.error('已经是第一行了!')
                return
            }
            const temp = this.screenSensorList[index - 1];
            this.screenSensorList.splice(index - 1, 1, row);
            this.screenSensorList.splice(index, 1, temp);
        },
        moveDown(row, index) {
            if (index === this.screenSensorList.length - 1) {
                this.$message.error('已经是最后一行了!')
                return
            }
            const temp = this.screenSensorList[index + 1];
            this.screenSensorList.splice(index + 1, 1, row);
            this.screenSensorList.splice(index, 1, temp);
        },
        tableChangeGateway(gatewayId, index) {
            this.screenSensorList[index]['sensorId'] = null
            listSelectByGatewayId(gatewayId).then(response => {
                this.screenSensorList[index]['sensorSelect'] = response.data
            })
        },
        deleteScreenLocation(row, index) {
            this.form.config1.splice(index, 1)
            for (let i = index; i < this.form.config1.length; i++) {
                this.form.config1[i].orderNum = i;
            }
        },
        deleteSensor(row, index) {
            this.screenSensorList.splice(index, 1)
        },
        getGatewayList() {
            listSelect().then(response => {
                this.gatewayList = []
                for (let item of response.data) {
                    let temp = {}
                    temp['value'] = item.gatewayId
                    temp['label'] = item.gatewayName
                    temp['serverOnline'] = item.serverOnline
                    this.gatewayList.push(temp)
                }
            })
        },
        submitScreenSensor() {
            let length = this.screenSensorList.length
            for (let i = 0; i < length; i++) {
                this.screenSensorList[i]['orderNum'] = i + 1
            }
            // if (arr.length === 0) {
            //     this.$message.error('请选择信息点')
            //     return
            // }
            addScreenSensor({ screenId: this.form.id, dataList: this.screenSensorList }).then(response => {
                this.$message.success('添加成功')
                // this.screenSensorOpen = false
            })
        },
        cancelScreenSensor() {
            this.screenSensorOpen = false
        }
    }
}
</script>
